package com.softserveinc.appwidget;

import java.text.SimpleDateFormat;
import java.util.List;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;

import com.softserveinc.MovieManagerActivity;
import com.softserveinc.MovieManagerApplication;
import com.softserveinc.R;
import com.softserveinc.WidgetConfigureActivity;
import com.softserveinc.model.Movie;

public class MovieManagerWidgetProvider extends AppWidgetProvider {
	protected static final String TAG = MovieManagerWidgetProvider.class
			.getSimpleName();

	public static final String APPWIDGET_CREATE = "com.softserveinc.APPWIDGET_CREATE";
	public static final String APPWIDGET_UPDATE = "com.softserveinc.APPWIDGET_UPDATE";

	public static final String APPWIDGET_DISPLAYED_MOVIE = "APPWIDGET_DISPLAYED_MOVIE";

	private MovieManagerWidgetMediator mediator;

	@Override
	public void onReceive(final Context context, final Intent intent) {
		super.onReceive(context, intent);

		mediator = ((MovieManagerApplication) context.getApplicationContext())
				.getMediator();

		if (intent.getAction().equals(APPWIDGET_CREATE)) {
			mediator.registerUIUpdateServiceIfNeeded(intent);
		} else if (intent.getAction().equals(APPWIDGET_UPDATE)) {
			updateWidgetUI(context, intent);
		}
	}

	@Override
	public void onDeleted(final Context context, final int[] appWidgetIds) {
		super.onDeleted(context, appWidgetIds);

		mediator = ((MovieManagerApplication) context.getApplicationContext())
				.getMediator();

		for (int appWidgetId : appWidgetIds) {
			mediator.unregisterWidgetServices(appWidgetId);
			mediator.clearWidgetPreferences(appWidgetId);
		}
	}

	private RemoteViews getMovieRemoteViews(final Context context,
			final Movie movie, final int appWidgetId) {
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_item);

		if (movie.getPoster() != null) {
			Log.w(TAG, "not null");
			views.setImageViewBitmap(R.id.icon_poster_on_widget,
					movie.getPoster());
		} else {
			Log.w(TAG, "null");
			views.setImageViewResource(R.id.icon_poster_on_widget,
					R.drawable.sample2);
		}

		views.setTextViewText(R.id.value_movie_title_in_widget,
				movie.getTitle());

		views.setImageViewResource(R.id.icon_restriction_on_widget, movie
				.getCertification().getValidIconID());

		SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
		views.setTextViewText(R.id.value_release_date_in_widget,
				format.format(movie.getReleaseDate()));

		views.setTextViewText(R.id.value_fan_rating_in_widget,
				"" + movie.getPopularity());

		setupShowDetailsClick(context, views, movie);

		setupShowPreferencesClick(context, appWidgetId, views);

		return views;
	}

	private void updateWidgetUI(final Context context, final Intent intent) {
		Log.d(TAG, "update widget ui");

		int appWidgetId = intent.getIntExtra(
				AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID);

		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget);

		views.removeAllViews(R.id.widget_view_flipper);

		int interval = ((MovieManagerApplication) context
				.getApplicationContext()).getWidgetSettingManager()
				.getUpdateUIPeriodInMilieconds(appWidgetId);

		views.setInt(R.id.widget_view_flipper, "setFlipInterval", interval);

		List<Movie> movies = intent
				.getParcelableArrayListExtra(APPWIDGET_DISPLAYED_MOVIE);

		for (Movie movie : movies) {
			RemoteViews nestedView = getMovieRemoteViews(context, movie,
					appWidgetId);
			views.addView(R.id.widget_view_flipper, nestedView);
		}

		try {
			AppWidgetManager appWidgetManager = AppWidgetManager
					.getInstance(context);

			appWidgetManager.updateAppWidget(appWidgetId, views);
		} catch (Exception e) {
			Log.e(TAG, "error " + e.getMessage(), e);
		}
	}

	private void setupShowPreferencesClick(final Context context,
			final int appWidgetId, final RemoteViews views) {
		Intent settingIntent = new Intent(context,
				WidgetConfigureActivity.class);
		settingIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
		Bundle extras = new Bundle();
		extras.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		settingIntent.putExtras(extras);
		settingIntent.setData(Uri
				.parse(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE
						+ appWidgetId));

		PendingIntent pendingIntentSettings = PendingIntent.getActivity(
				context, 0, settingIntent, 0);

		views.setOnClickPendingIntent(R.id.button_setting_on_widget,
				pendingIntentSettings);
	}

	private void setupShowDetailsClick(final Context context,
			final RemoteViews views, final Movie movie) {
		Intent detailsIntent = new Intent(context, MovieManagerActivity.class);
		detailsIntent.putExtra(APPWIDGET_DISPLAYED_MOVIE, movie);
		detailsIntent.setData(Uri.parse(movie.toString()));
		detailsIntent.setAction(MovieManagerActivity.ACTION_MOVIE_DETAILS);

		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				detailsIntent, 0);
		views.setOnClickPendingIntent(R.id.layout_widget, pendingIntent);
	}
}
